<template>
  <div class="cityInput">
    <el-input
        v-model="address"
        placeholder="请输入城市名称"
        clearable
        size="large"
        @input="handleSeach"
    />

    <ul v-if="searchData && address.toString().trim()">
      <p @click="visitDetails">{{ info }}</p>
    </ul>
  </div>
</template>

<script setup>
import {ref, defineEmits} from 'vue'
import {getAdcodeByCity} from "@/api/index.js";
import router from "@/router/index.js";

const address = ref('')
const info = ref('')
const emit = defineEmits()

const searchData = ref(false)

const visitDetails = async () => {
  //触发请求
  let res = await getAdcodeByCity(address.value);
  let adcode = res.geocodes[0].adcode
  router.push({path: `/${adcode}`})
}

const handleSeach = async () => {
  if (address.value.toString().trim()) {
    let res = await getAdcodeByCity(address.value);
    searchData.value = true
    if (res.info === 'OK' && res.geocodes.length > 0) {
      info.value = res.geocodes[0].city
    } else {
      info.value = '似乎没有找到你查找的城市'
    }
  } else {
    searchData.value = false
  }

  // 向父组件发送输入框是否为空的状态
  emit('update:address', address.value)
}

</script>

<style scoped lang="scss">
.cityInput :deep(.el-input__wrapper) {
  border: none;
  border-bottom: 1px solid white;
  border-radius: 0;
  background-color: transparent;
  box-shadow: none !important;
  color: white;
  padding: .5rem .25rem;
  height: 41px;
}

.cityInput :deep(.el-input__inner) {
  background-color: transparent;
  color: white;
}

.cityInput :deep(.el-input__inner::placeholder) {
  font-size: 16px;
  font-family: "Microsoft YaHei", sans-serif;
  line-height: 41px;
}

.cityInput ul {
  height: 40px;
  padding: .5rem .25rem;
  background-color: rgb(0 78 113 / 1);
  margin-top: 5px;
  cursor: pointer; /* 鼠标悬停时显示手型光标 */

  p {
    color: white;
  }
}
</style>